/* Copyright (C) 
 * 
 * Disclaim
 * This program is the property of AI Speech Ltd. It shall be communicated to
 * authorized personnel only. It is not to be disclosed outside the group without
 * prior written consent. If you are not sure if you’re authorized to read this
 * program, please contact info@aispeech.com before reading.
 * 
 */

/**
 * @file wtk_utils_array.c
 * 
 * @author wxm71(weixing.mei@aispeech.com)
 * 
 * @version 0.0.1
 * 
 * @date 2014-12-15
 */

#include "wtk_utils.h"
#include "wtk_utils_array.h"


wtk_array_t* wtk_array_copy(wtk_array_t *src, wtk_heap_t *heap) {
    wtk_array_t *dst = wtk_array_new_h(heap, src->nslot, src->slot_size);
    memcpy(dst->slot, src->slot, src->slot_size*src->nslot);
    dst->nslot = src->nslot;

    return dst;
}


wtk_array_t* wtk_array_deep_copy(wtk_array_t *src, wtk_array_cp_handler_t hand, void *data,  wtk_heap_t *heap)  {
    wtk_array_t  *dst = wtk_array_new_h(heap, src->nslot, src->slot_size);

    int i;
    void **ptr;
    void *new;
    for(i=0, ptr=src->slot; i<src->nslot; ++i, ++ptr) {
        new = hand(*ptr, data, heap);
        wtk_array_push2(dst, &new);
    }

    return dst;
}


int wtk_utils_str_array_has(wtk_array_t *arr, char *data, int len) {
    int i;
    wtk_string_t *str;
    for(i=0; i<arr->nslot; ++i) {
        str = wtk_utils_array_get_val(arr, i, wtk_string_t*);

        if(wtk_utils_string_equ(str, data, len)) {
            return 1;
        }
    }

    return 0;
}


void wtk_utils_str_array_uniq_push(wtk_array_t *arr, char *data, int len) {
    wtk_string_t *str;
    if(!wtk_utils_str_array_has(arr, data, len)) {
        str = wtk_heap_dup_string(arr->heap, data, len);
        wtk_array_push2(arr, &str);
    }
}


void wtk_utils_str_array_join(wtk_array_t *arr, char *sep, int len, wtk_strbuf_t *buf, int reset) {
    if(reset) {
        wtk_strbuf_reset(buf);
    }

    if(NULL==arr || arr->nslot<1 || NULL==buf) {
	return ;
    }

    int flag = 0;       // whether have push something new in buf
    wtk_string_t *val;

    int i;
    for(i=0; i<arr->nslot; ++i) {
	val = wtk_utils_array_get_val(arr, i, wtk_string_t*);
	wtk_strbuf_push(buf, val->data, val->len);

        wtk_strbuf_push(buf, sep, len);
        flag = 1;

	if(buf->pos>4096) {
	    wtk_utils_warn("total length of array are more than 4096, will throw left elements");
	    break;
	}
    }

    if(1==flag) {
        buf->pos -= len;
    }
}

